package iip

import (
    "github.com/gin-gonic/gin"
    "iip/iip/model"
    "iip/lib"
)


func (s *IIP) StockProductPagedList(c *gin.Context) {

    query := &struct {
        Page     int    `form:"page" binding:"required,gte=1" json:"page"`
        PageSize int    `form:"pagesize" binding:"required,gte=1" json:"pagesize"`
        Order    string `form:"order" json:"order"`
    }{}
    if err := c.ShouldBindQuery(query); err != nil {
        s.logger.Error(err.Error())
        lib.JsonError(c, err.Error())
        return
    }
    if query.Order != "asc" && query.Order != "desc" {
        query.Order = "asc"
    }




    var total int64
    if err := s.gorm().Model(&model.Product{}).Count(&total).Error; err != nil {
        s.logger.Error(err.Error())
        lib.JsonError(c, err.Error())
        return
    }

    var lst []*model.Product
    if err := s.gorm().Limit(query.PageSize).Offset(query.PageSize * (query.Page - 1)).Order("id " + query.Order).Find(&lst).Error; err != nil {
        s.logger.Error(err.Error())
        lib.JsonError(c, err.Error())
        return
    } else {
        s.logger.Info("query location paged list")
        lib.JsonPagedData(c, total, query.Page, query.PageSize, lst)
    }
}

func (s *IIP) StockProductByID(c *gin.Context) {
    req := &struct {
        ID int64 `uri:"id"`
    }{}
    if err := c.ShouldBindUri(req); err != nil {
        s.logger.Error(err.Error())
        lib.JsonError(c, err.Error())
        return
    }

    row := model.Product{}
    if err := s.gorm().Debug().Where(&model.Product{ID: req.ID}).First(&row).Error; err != nil {
        s.logger.Error(err.Error())
        lib.JsonError(c, err.Error())
        return
    } else {
        s.logger.Info("query location by id ", req.ID)
        lib.JsonData(c, row)
        return
    }
}
